package com.gitee.melin.bee.core.fs.impl;

import com.gitee.melin.bee.core.fs.FileSystem;
import com.gitee.melin.bee.core.fs.FsConnectionInfo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.region.Region;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TencentCosFileSystem implements FileSystem {
    private static final Logger LOGGER = LoggerFactory.getLogger(TencentCosFileSystem.class);

    @Override
    public String testConnection(FsConnectionInfo connectionInfo) {
        COSCredentials cred =
                new BasicCOSCredentials(connectionInfo.getAccessKeyId(), connectionInfo.getSecretAccessKey());

        Region region = new Region(connectionInfo.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);

        String bucket = connectionInfo.getBucket();
        if (StringUtils.isNotBlank(bucket)) {
            List<String> buckets = this.queryBuckets(cosClient);
            if (!buckets.contains(connectionInfo.getBucket())) {
                throw new IllegalArgumentException("bucket not exist: " + bucket);
            }
        }

        cosClient.shutdown();
        return "Success";
    }

    @Override
    public List<String> queryBuckets(FsConnectionInfo connectionInfo) {
        COSCredentials cred =
                new BasicCOSCredentials(connectionInfo.getAccessKeyId(), connectionInfo.getSecretAccessKey());

        Region region = new Region(connectionInfo.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);

        List<String> buckets = this.queryBuckets(cosClient);

        cosClient.shutdown();
        return buckets;
    }

    private List<String> queryBuckets(COSClient cosClient) {
        return cosClient.listBuckets().stream().map(Bucket::getName).collect(Collectors.toList());
    }
}
